package com.fastloan.utils;

import com.itextpdf.io.util.UrlUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;

/**
 * @author chenkai
 * createTime 2017-12-2017/12/11 15:46
 */
public class UrlEncryptUtil {

    private static final String KEY = "Mw6qPt&3AD&QkJR";
    private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtil.class);

    public static String enCryptAndEncode(String content) {
        if (!StringUtils.isBlank(content)) {
            try {
                byte[] sourceBytes = enCryptAndEncode(content, KEY);
                return Base64.encodeBase64URLSafeString(sourceBytes);
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
                return content;
            }
        }
        return null;
    }


    /**
     * 加密函数
     *
     * @param content 加密的内容
     * @param strKey  密钥
     * @return 返回二进制字符数组
     * @throws Exception
     */
    public static byte[] enCryptAndEncode(String content, String strKey) throws Exception {
        if (!StringUtils.isBlank(content)) {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(KEY.getBytes());
            keyGenerator.init(128, random);

            SecretKey desKey = keyGenerator.generateKey();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            return cipher.doFinal(content.getBytes("UTF-8"));
        }
        return null;
    }

    public static String deCryptAndDecode(String content) throws Exception {
        if (!StringUtils.isBlank(content)) {
            byte[] targetBytes = Base64.decodeBase64(content);
            return deCryptAndDecode(targetBytes, KEY);
        }
        return null;
    }

    /**
     * 解密函数
     *
     * @param src    加密过的二进制字符数组
     * @param strKey 密钥
     * @return
     * @throws Exception
     */
    public static String deCryptAndDecode(byte[] src, String strKey) throws Exception {
        if (src != null) {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(KEY.getBytes());
            keyGenerator.init(128, random);

            SecretKey desKey = keyGenerator.generateKey();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            byte[] cByte = cipher.doFinal(src);
            return new String(cByte, "UTF-8");
        }
        return null;
    }

}
